/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import model.Currency;

/**
 *
 * @author Guillaume
 */
@Stateless
public class ConverterFacade {
    
    @PersistenceContext(unitName = "hw4PU")
    private EntityManager em;
    @EJB
    private Converter converter;
    
    public void ConverterFacade(){
        this.storeCurrencies();
    }

    public void storeCurrencies() {
        Currency cur = new Currency("euro", 1.32);
        em.persist(cur);
        cur = new Currency("dollar", 1);
        em.persist(cur);
        cur = new Currency("sek", 0.143);
        em.persist(cur);
        cur = new Currency("yen", 0.0129);
        em.persist(cur);
    }
    
    public List<Currency> getStoredCurrencies(){
        Query queryFrom = em.createNamedQuery("findStoredCurrencies",Currency.class);
        List<Currency> storedCurrencies = queryFrom.getResultList();
        return storedCurrencies;
    }
    
    public void setCurrencies(){
        
    }

    public void convert(Float amount, String fromCurrency, String toCurrency) throws Exception {
        if( amount < 0){
            throw new Exception("Can't convert negative amount");
        }
         System.out.println("Rate from: "+fromCurrency);
        Query queryFrom = em.createNamedQuery("findChangeRate",Currency.class);
        queryFrom.setParameter("currencyName", fromCurrency);
        List<Currency> fromCurListChange = queryFrom.getResultList();
        Currency currencyFrom = fromCurListChange.get(0);
        Double fromCurChangeRate = currencyFrom.getChange();
        System.out.println("Rate from: "+ fromCurChangeRate+ fromCurrency);
        
        
        Query queryTo = em.createNamedQuery("findChangeRate",Currency.class);
        queryTo.setParameter("currencyName", toCurrency);
        List<Currency> toCurListChange = queryTo.getResultList();
        Currency currencyTo = toCurListChange.get(0);
        Double toCurChangeRate = currencyTo.getChange();
        System.out.println("Rate to: "+ toCurChangeRate+toCurrency);

        double change = fromCurChangeRate / toCurChangeRate;
        System.out.println("Change: "+ change);
        converter.convert(amount, change);
    }

    public double convertedAmount() {
        System.out.println("Converted CF: "+converter.getConvertAmount());
        return converter.getConvertAmount();
    }
     
}
